package com.csk.zsk.compents.interceptor;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.csk.zsk.compents.utils.Constants;

/**
 * Servlet Filter implementation class HtmlFilter
 */
public class HtmlFilter implements Filter {

	@SuppressWarnings("unused")
	private FilterConfig filterConfig;
	@SuppressWarnings("unused")
	private FilterChain chain;
	private HttpServletRequest request;
	private HttpServletResponse response;

	public void destroy() {
		this.filterConfig = null;
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		this.chain = chain;
		this.request = (HttpServletRequest) servletRequest;
		this.response = ((HttpServletResponse) servletResponse);

		HttpSession session = request.getSession();
		if (session != null
				&& session.getAttribute(Constants.USER_SESSION) != null) {
			chain.doFilter(request, response);
		} else {
			String url = request.getServletPath();
			if (url != null && !url.equals("/login.html")) {
				String path = request.getContextPath();
				String basePath = request.getScheme() + "://"
						+ request.getServerName() + ":"
						+ request.getServerPort() + path + "/";

				response.sendRedirect(basePath + "login.html");
			} else {
				chain.doFilter(request, response);
			}
		}

	}

}
